package com.awakensoftware.hunterserver.transformers;

import org.springframework.beans.factory.annotation.Autowired;

import com.awakensoftware.communicationprotocol.contractobjects.ContractObjectBase;
import com.awakensoftware.hunterserver.repositories.ServerEntityRepositoryBase;
import com.awakensoftware.hunterserver.serverentities.ServerEntityBase;

public abstract class TransformerBase<TServerEntityType extends ServerEntityBase, TContractObjectType extends ContractObjectBase> {

	@Autowired
	private ServerEntityRepositoryBase<TServerEntityType> serverEntityRepository;

	public abstract TServerEntityType transformFromContractToServerEntity(TContractObjectType contractObject);

	public abstract TContractObjectType transformFromServerEntityToContractObject(TServerEntityType serverEntity);

	// ContractObject -> ServerEntity
	protected void doCompleteTransformFromContractObjectToServerEntity(TContractObjectType contractObject,
			TServerEntityType serverEntity) {
		doMinimalTransformFromContractObjectToServerEntity(contractObject, serverEntity);
		doTypeSpecificTransformFromContractObjectToServerEntity(contractObject, serverEntity);
	}
	
	protected void doMinimalTransformFromContractObjectToServerEntity(TContractObjectType contractObject,
			TServerEntityType serverEntity) {
		serverEntity.setId(contractObject.getInternalId());
		serverEntity.setName(contractObject.getName());
	}

	protected abstract void doTypeSpecificTransformFromContractObjectToServerEntity(TContractObjectType contractObject,
			TServerEntityType serverEntity);
	
	// ServerEntity -> ContractObject
	protected void doCompleteTransformFromServerEntityToContractObject(TContractObjectType contractObject,
			TServerEntityType serverEntity) {
		doMinimalTransformFromServerEntityToContractObject(contractObject, serverEntity);
		doTypeSpecificTransformFromServerEntityToContractObject(contractObject, serverEntity);
	}
	
	protected void doMinimalTransformFromServerEntityToContractObject(TContractObjectType contractObject,
			TServerEntityType serverEntity) {
		contractObject.setInternalId(serverEntity.getId());
		contractObject.setName(serverEntity.getName());
	}
	
	protected abstract void doTypeSpecificTransformFromServerEntityToContractObject(TContractObjectType contractObject,
			TServerEntityType serverEntity);

	protected TServerEntityType tryGetExistingServerEntityById(long id) {
		return serverEntityRepository.getById(id);
	}

}
